package com.entor.springboot201912.util;

import com.cloopen.rest.sdk.CCPRestSmsSDK;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Random;

/**
 * 短信发送工具
 */
public class SmsUtil {
    /**
     * 发送手机短信
     * @param to 发送的号码
     * @param session
     * @return
     */
    public static boolean sendPhoneCode(String to, HttpSession session){
        boolean flat = false;
        try{
            //声明随机数对象
            Random r = new Random();
            int code = r.nextInt(900000)+100000;
            //设置有效时间
            session.setMaxInactiveInterval(300);//有效期为5分钟
            //存入session会话
            session.setAttribute("phoneCode",to+"-"+code);
            //声明短信发送对象
            CCPRestSmsSDK sdk = new CCPRestSmsSDK();
            sdk.init("app.cloopen.com","8883");//初始化
            String sid = "8a48b5515249574b015252af55751033";
            String token = "ed8667cafc7a46649781225d8a36b823";
            String aid = "8a48b5515249574b015252c3cbf31091";

            sdk.setAccount(sid,token);
            sdk.setAppId(aid);

            //执行发送
            HashMap<String,Object> map =
                    sdk.sendTemplateSMS(to,"1",new String[]{code+"","5"});
            System.out.println("验证码："+code);
            System.out.println("发送结果："+map);
            if(map.get("statusCode").equals("000000")){
                System.out.println("短信发送成功");
                flat = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flat;
    }

    public static void main(String[] args) {
        //sendPhoneCode("");
    }
}
